Date.prototype.format = function(format) {
    var o = {
	"M+" : this.getMonth() + 1, // month
	"d+" : this.getDate(), // day
	"h+" : this.getHours(), // hour
	"m+" : this.getMinutes(), // minute
	"s+" : this.getSeconds(), // second
	"q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
	"S" : this.getMilliseconds()
    // millisecond
    };
    if (/(y+)/.test(format)) {
	format = format.replace(RegExp.$1, (this.getFullYear() + "")
		.substr(4 - RegExp.$1.length));
    }
    for ( var k in o) {
	if (new RegExp("(" + k + ")").test(format)) {
	    format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
		    : ("00" + o[k]).substr(("" + o[k]).length));
	}
    }
    return format;
};

var TT = TAOTAO = {
    // 编辑器参数
    kingEditorParams : {
	// 指定上传文件参数名称
	filePostName : "uploadFile",
	// 指定上传文件请求的url。
	uploadJson : '/pic/upload',
	// 上传类型，分别为image、flash、media、file
	dir : "image"
    },
    // 格式化时间
    formatDateTime : function(val, row) {
	var now = new Date(val);
	return now.format("yyyy-MM-dd hh:mm:ss");
    },
    // 格式化连接
    formatUrl : function(val, row) {
	if (val) {
	    return "<a href='" + val + "' target='_blank'>查看</a>";
	}
	return "";
    },
    // 格式化价格
    formatPrice : function(val, row) {
	return (val / 1000).toFixed(2);
    },
    // 格式化商品的状态
    formatItemStatus : function formatStatus(val, row) {
	if (val == 1) {
	    return '正常';
	} else if (val == 2) {
	    return '<span style="color:red;">下架</span>';
	} else {
	    return '未知';
	}
    },

    init : function(data) {
	// 初始化图片上传组件
	this.initPicUpload(data);
	// 初始化选择类目组件
	this.initItemCat(data);
    },
    // 初始化图片上传组件
    initPicUpload : function(data) {
	$(".picFileUpload")
		.each(
			function(i, e) {
			    var _ele = $(e);
			    _ele.siblings("div.pics").remove();
			    _ele
				    .after('\
    			<div class="pics">\
        			<ul></ul>\
        		</div>');
			    // 回显图片
			    if (data && data.pics) {
				var imgs = data.pics.split(",");
				for ( var i in imgs) {
				    if ($.trim(imgs[i]).length > 0) {
					_ele
						.siblings(".pics")
						.find("ul")
						.append(
							"<li><a href='"
								+ imgs[i]
								+ "' target='_blank'><img src='"
								+ imgs[i]
								+ "' width='80' height='50' /></a></li>");
				    }
				}
			    }
			    // 给“上传图片按钮”绑定click事件
			    $(e)
				    .click(
					    function() {
						var form = $(this)
							.parentsUntil("form")
							.parent("form");
						// 打开图片上传窗口
						KindEditor
							.editor(
								TT.kingEditorParams)
							.loadPlugin(
								'multiimage',
								function() {
								    var editor = this;
								    editor.plugin
									    .multiImageDialog({
										clickFn : function(
											urlList) {
										    var imgArray = [];
										    KindEditor
											    .each(
												    urlList,
												    function(
													    i,
													    data) {
													imgArray
														.push(data.url);
													form
														.find(
															".pics ul")
														.append(
															"<li><a href='"
																+ data.url
																+ "' target='_blank'><img src='"
																+ data.url
																+ "' width='80' height='50' /></a></li>");
												    });
										    form
											    .find(
												    "[name=image]")
											    .val(
												    imgArray
													    .join(","));
										    editor
											    .hideDialog();
										}
									    });
								});
					    });
			});
    },

    // 初始化选择类目组件
    initItemCat : function(data) {
	$(".selectItemCat")
		.each(
			function(i, e) {
			    var _ele = $(e);
			    if (data && data.cid) {
				_ele.after("<span style='margin-left:10px;'>"
					+ data.cid + "</span>");
			    } else {
				_ele
					.after("<span style='margin-left:10px;'></span>");
			    }
			    _ele
				    .unbind('click')
				    .click(
					    function() {
						$("<div>")
							.css({
							    padding : "5px"
							})
							.html("<ul>")
							.window(
								{
								    width : '500',
								    height : "450",
								    modal : true,
								    closed : true,
								    iconCls : 'icon-save',
								    title : '选择类目',
								    onOpen : function() {
									var _win = this;
									$("ul",
										_win)
										.tree(
											{
											    url : '/item/cat/list',
											    animate : true,
											    onClick : function(
												    node) {
												if ($(
													this)
													.tree(
														"isLeaf",
														node.target)) {
												    // 填写到cid中
												    _ele
													    .parent()
													    .find(
														    "[name=cid]")
													    .val(
														    node.id);
												    _ele
													    .next()
													    .text(
														    node.text)
													    .attr(
														    "cid",
														    node.id);
												    $(
													    _win)
													    .window(
														    'close');
												    if (data
													    && data.fun) {
													data.fun
														.call(
															this,
															node);
												    }
												}
											    }
											});
								    },
								    onClose : function() {
									$(this)
										.window(
											"destroy");
								    }
								}).window(
								'open');
					    });
			});
    },

    createEditor : function(select) {
	return KindEditor.create(select, TT.kingEditorParams);
    },

    /**
     * 创建一个窗口，关闭窗口后销毁该窗口对象。<br/>
     * 
     * 默认：<br/> width : 80% <br/> height : 80% <br/> title : (空字符串) <br/>
     * 
     * 参数：<br/> width : <br/> height : <br/> title : <br/> url : 必填参数 <br/>
     * onLoad : function 加载完窗口内容后执行<br/>
     * 
     * 
     */
    createWindow : function(params) {
	$("<div>").css({
	    padding : "5px"
	}).window({
	    width : params.width ? params.width : "80%",
	    height : params.height ? params.height : "80%",
	    modal : true,
	    title : params.title ? params.title : " ",
	    href : params.url,
	    onClose : function() {
		$(this).window("destroy");
	    },
	    onLoad : function() {
		if (params.onLoad) {
		    params.onLoad.call(this);
		}
	    }
	}).window("open");
    },

    closeCurrentWindow : function() {
	$(".panel-tool-close").click();
    },

    changeItemParam : function(node, formId) {
	$
		.getJSON(
			"/item/param/cid/" + node.id,
			function(data) {
			    if (data.status == 200 && data.data) {
				$("#" + formId + " .params").show();
				var paramData = JSON.parse(data.data.paramData);
				var html = "<ul>";
				for ( var i in paramData) {
				    var pd = paramData[i];
				    html += "<li><table>";
				    html += "<tr><td colspan=\"2\" class=\"group\">"
					    + pd.group + "</td></tr>";

				    for ( var j in pd.params) {
					var ps = pd.params[j];
					html += "<tr><td class=\"param\"><span>"
						+ ps
						+ "</span>: </td><td><input autocomplete=\"off\" type=\"text\"/></td></tr>";
				    }

				    html += "</li></table>";
				}
				html += "</ul>";
				$("#" + formId + " .params td").eq(1)
					.html(html);
			    } else {
				$("#" + formId + " .params").hide();
				$("#" + formId + " .params td").eq(1).empty();
			    }
			});
    },
    getSelectionsIds : function(select) {
	var list = $(select);
	var sels = list.datagrid("getSelections");
	var ids = [];
	for ( var i in sels) {
	    ids.push(sels[i].id);
	}
	ids = ids.join(",");
	return ids;
    },

    /**
     * 初始化单图片上传组件 <br/> 选择器为：.onePicUpload <br/> 上传完成后会设置input内容以及在input后面追加<img>
     */
    initOnePicUpload : function() {
	$(".onePicUpload")
		.click(
			function() {
			    var _self = $(this);
			    KindEditor
				    .editor(TT.kingEditorParams)
				    .loadPlugin(
					    'image',
					    function() {
						this.plugin
							.imageDialog({
							    showRemote : false,
							    clickFn : function(
								    url, title,
								    width,
								    height,
								    border,
								    align) {
								var input = _self
									.siblings("input");
								input
									.parent()
									.find(
										"img")
									.remove();
								input.val(url);
								input
									.after("<a href='"
										+ url
										+ "' target='_blank'><img src='"
										+ url
										+ "' width='80' height='50'/></a>");
								this
									.hideDialog();
							    }
							});
					    });
			});
    }
};

function setCookie(name, value) {
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}

function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

function checkCookie() {
    if (getCookie("username") == null || getCookie("rolename") == null) {
        alert("未登录!");
        window.location.href = "openlogin";
    }
}

function clearCookie() {
    delCookie("username");
    delCookie("rolename");
    window.location.href = "openlogin";
}

// 改变layout头部
$.extend($.fn.panel.methods, {
		changeHeaderToUser:function(jq,options){
			var header = jq.panel('header');
			// 设置header的高度
			header.css('height',options.height);
			if(options.userInfo){
			// 删除原有的title div
			header.children("div.panel-title").remove();
			// 添加新的header
			header.prepend("<div class='row'></div>");
			// 添加新的图片和信息
			header.children("div.row").prepend("<div class='col-4 "+options.userInfo.imgCls+"' style='width:48px;height: 48px;'></div>");
			header.children("div.row").append("<div class='col-8 listmenu'>"+
			"<ul class='panel-title'><li>您好，</li>"+"<li>"+options.userInfo.userName+"</li><li><a href='javascript:void(0)' onclick='javascript:logout(\""+
			options.logoutUrl+
			"\")'>退出</a></li></ul>"+
			"</div>");
			}
			if(options.resize){
			jq.resize();
			}
		}
});

function createAccordion(mainNavId){
		// 删除#RightAccordion所有的子
		var pnl = $("#RightAccordion").accordion("panels");  
    	var titles='';  
    	if (pnl){  
        $.each(pnl, function(i) {  
            var title = pnl[i].panel("options").title;  
            titles += title+',';  
        	});  
    	}
    	var arr_title = new Array();   
    	arr_title = titles.split(",");  
    	for (i=0;i<arr_title.length ;i++ ){   
        if(arr_title[i] != ""){
            $('#RightAccordion').accordion("remove",arr_title[i]);  
        	}  
    	}
		$("#RightAccordion").accordion({ //初始化accordion
		fillSpace : true,
		fit : true,
		border : false,
		animate : true
	    });
	    $.get("nav/treenav/"+mainNavId+"/0", //获取第一层目录
	    function(data) {
			$.each(data,function(i, e) {//循环创建手风琴的项
						    var id = e.id;
						    $('#RightAccordion').accordion('add',
								    {
									title : e.text,
									content : "<ul id='tree"+id+"' ></ul>",
									selected : true,
									iconCls : e.iconCls
								    });
						    $.parser.parse();
						    $.get("nav/treenav/"+mainNavId+"/"+id,
								    function(data) {//循环创建树的项
									$("#tree"+id).tree({
									data : data,
									onBeforeExpand : function(node,param) {
										$("#tree"+ id).tree('options').url = "nav/treenav/" + 
										mainNavId +"/"+node.id;
										},
									onClick : function(node) {
										if (node.state == 'closed') {
										$(this).tree('expand',node.target);
											} else if (node.state == 'open') {
											//判断排除此open状态的节点是否为叶子节点，如是则打开对应tab
											if ($("#tree"+ id).tree("isLeaf",node.target)) {
													var tabTitle = node.text;
													var url = node.attributes.url;
													var icon = node.iconCls;
													addTab(tabTitle,url,icon);
												    } else {
													$(this).tree('collapse',node.target);
												    }
												}
											   }
											});
								    }, 'json');
						});
						_toCenter();
			    }, "json");
			    	function _toCenter(){
			    		var panelTitls = $("#RightAccordion").find('>.panel>.accordion-header>.panel-title');
						if (panelTitls.length){  
        					$.each(panelTitls, function(i) {  
            					panelTitls.css({"position":"absolute","top":"50%","transform":"translateY(-50%)"});
        					});  
    					} 
			    	}
			    }

function addTab(tabTitle, url, icon) {
	    var tabs = $("#tabs");
	    var tab = tabs.tabs("getTab", tabTitle);
	    if (tab) {
		tabs.tabs("select", tabTitle);
	    } else {
		tabs.tabs('add', {
		    title : tabTitle,
		    href : "page/" + url,
		    closable : true,
		    iconCls : icon,
		    bodyCls : "content"
		});
	    }
	}

//动态创建导航主菜单a
function createMainNav(){
	// 在主菜单div上添加一个ui
	$("#mainnav").append("<div class='navmenu'></div>");
	$("#mainnav").children("div.navmenu").append("<ul class='fa-ul'></div>");
	var ul = $("#mainnav").children("div.navmenu").children("ul.fa-ul");
	$.get("nav/mainnav/0",function(data){
		$.each(data,function(i, e) {
			var id = e.id;
			ul.append("<li><a id='mainnav"+id+ 
			"' href='javascript:void(0);' onclick='selectMainNav(this);'>"+
			"<span class='"+ e.iconCls +
			"'><div>"+e.text+"</div>"+
			"</span></a></li>");
		});
		// 默认选择最右边a标签主菜单
		selectMainNav("a[id^='mainnav']:first");
	},"json");
}

// 点击主菜单事件
function selectMainNav(tag){
	var classStr = $(tag).attr('class');
	if(!classStr || classStr.indexOf('active') < 0){
		$("a[id^='mainnav']").removeClass('active');
		$(tag).addClass('active');
		var mainNavId = parseInt($(tag).attr('id').replace(/[^0-9]/ig,""));
		createAccordion(mainNavId);
	}
}

$.ajaxSetup({
        complete : function(data, TS) {
            //对返回的数据data做判断
            //403是后台拦截器那儿定义的，
            if (data.status == 403) {
                //session过期的话，就location到一个页面
                $.messager.alert('提示信息', "登陆超时！请重新登陆！", 'info',function(){
	                   window.location.href = '/';
	               });
                return;
            }
        }
    });
// 退出登录
function logout(urlStr){
	$.messager.confirm('退出', '您想要退出该系统吗？', function(r){
		if (r){
			$.ajax({
			type : "get",
			async:false,
			url : "/"+urlStr,
			success : function(result) {
	    // 跳转主页
	    window.location.href = "/";
			}
		});
		}
	});
}